const express = require("express");
const router = express.Router();
const path = require("path");
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const fs = require("fs");
const crypto = require("crypto");
const CryptoJS = require("crypto-js");
const FormData = require("form-data");
const axios = require("axios");

// 配置 multer 的存储设置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件上传目录
        cb(null, "/home/wwwroot/default/porter/node-server/files");
    },
    filename: function (req, file, cb) {
        // 生成文件名
        cb(null, Date.now() + "-" + file.originalname);
    },
});
const upload = multer({ storage: storage });
// 创建文件上传的 POST 接口
router.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;
    if (!file) {
        return res.status(400).send("请上传一个文件。");
    }

    // 构建文件存储路径
    const fileUrl = `https://chatai-pro.wecall.info/files/${file.filename}`;

    // 返回文件存储地址
    res.send({
        code: 0,
        message: "文件上传成功",
        fileUrl: fileUrl,
    });
});

router.post('/getUsreList', async (req, res) => {
    let sql = `select * from porter_user`
    await pool.query(sql, async (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        // 创建一个包含所有异步操作的 Promise 数组
        let promises = result.map(async (element) => {
            if (element.invitation_rewards) {
                element.invitation_rewards = element.invitation_rewards.toFixed(6);
            }
            if (element.withdrawn_rewards) {
                element.withdrawn_rewards = element.withdrawn_rewards.toFixed(6);
            }
            if (element.remaining_withdrawable_rewards) {
                element.remaining_withdrawable_rewards = element.remaining_withdrawable_rewards.toFixed(6);
            }
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            return element; // 返回处理后的 element
        });

        // 等待所有异步操作完成，并获得结果数组
        let updatedResult = await Promise.all(promises);

        res.send(
            utils.returnData({
                data: result, // 返回更新后的结果
            })
        );
    });
})

router.post('/getUsreInfo', async (req, res) => {
    const { id } = req.body
    let sql = `select * from porter_user where id = '${id}'`
    await pool.query(sql, async (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        // 创建一个包含所有异步操作的 Promise 数组
        let promises = result.map(async (element) => {
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            if (element.invitation_rewards) {
                element.invitation_rewards = element.invitation_rewards.toFixed(6);
            }
            if (element.withdrawn_rewards) {
                element.withdrawn_rewards = element.withdrawn_rewards.toFixed(6);
            }
            if (element.remaining_withdrawable_rewards) {
                element.remaining_withdrawable_rewards = element.remaining_withdrawable_rewards.toFixed(6);
            }
            return element; // 返回处理后的 element
        });

        // 等待所有异步操作完成，并获得结果数组
        let updatedResult = await Promise.all(promises);

        res.send(
            utils.returnData({
                data: result[0], // 返回更新后的结果
            })
        );
    });
})

//提现
router.post('/withdraw', async (req, res) => {
    const { email, amount, id } = req.body
    let sql = `select * from porter_user where id = ?`
    let arr = [id]
    let row = await mysqlHandel(sql, arr)
    if (amount > row[0].remaining_withdrawable_rewards) return res.send({ code: 1, msg: 'Insufficient balance!' })
    const newWithdrawnRewards = Number(row[0].withdrawn_rewards) + Number(amount); //已提现
    const newRemainingWithdrawableRewards = Number(row[0].invitation_rewards) - Number(newWithdrawnRewards);//剩余可提现
    let sql1 = `UPDATE porter_user 
             SET withdrawn_rewards = ?,remaining_withdrawable_rewards = ?, update_date = ?
             WHERE id = ?`;
    let arr1 = [newWithdrawnRewards, newRemainingWithdrawableRewards, formatDate(new Date()), id]
    //用户表扣除金额
    let row1 = await mysqlHandel(sql1, arr1)
    //提现记录表 添加提现信息
    let appComment = {}
    appComment.id = utils.createId();
    appComment.uid = id;
    appComment.paypal_account = email;
    appComment.amount = amount;
    appComment.create_date = utils.formatDate(new Date());
    appComment.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql(
        "porder_withdraw_list",
        appComment
    );
    let result = await utils.query(text, values);
    if (result.affectedRows == 1) {
        res.send({ code: 0, msg: "success" });
    } else {
        res.send(utils.returnData({ code: -1, err, req }));
    }
})

// 提现记录
router.post('/withdrawListById', async (req, res) => {
    const { id } = req.body
    let sql = `select * from porder_withdraw_list where uid = ?`
    let arr = [id]
    let row = await mysqlHandel(sql, arr)
    row.forEach(element => {
        if (!element.reason) {
            element.reason = '-'
        }
        element.create_date = moment(element.create_date)
            .tz("Asia/Shanghai")
            .format("YYYY-MM-DD HH:mm:ss");
        element.update_date = moment(element.update_date)
            .tz("Asia/Shanghai")
            .format("YYYY-MM-DD HH:mm:ss");
        if (element.amount) {
            element.amount = Number(element.amount).toFixed(6);
        }
    })
    res.send(
        utils.returnData({
            data: row
        })
    );

})
// 提现记录
router.post('/withdrawList', async (req, res) => {
    let sql = `select * from porder_withdraw_list`
    let arr = []
    let row = await mysqlHandel(sql, arr)
    row.forEach(element => {
        if (!element.reason) {
            element.reason = '-'
        }
        element.create_date = moment(element.create_date)
            .tz("Asia/Shanghai")
            .format("YYYY-MM-DD HH:mm:ss");
        element.update_date = moment(element.update_date)
            .tz("Asia/Shanghai")
            .format("YYYY-MM-DD HH:mm:ss");
        if (element.amount) {
            element.amount = Number(element.amount).toFixed(6);
        }
    })
    res.send(
        utils.returnData({
            data: row
        })
    );

})

//审核提现记录
router.post('/editWithdraw', async (req, res) => {
    const { id, amount, uid, status, reason } = req.body
    if (status == 1) {
        let sql = `UPDATE porder_withdraw_list SET status = '1'  ,update_date = '${formatDate(
            new Date()
        )}' where id = ?`
        let arr = [id]
        let row = await mysqlHandel(sql, arr)
        res.send({ code: 0, msg: 'success' })
    } else {
        let sql1 = `UPDATE porder_withdraw_list SET status = '2' , reason = '${reason}',update_date = '${formatDate(
            new Date()
        )}' where id = ?`
        let sq = `update porter_withdraw_list set status = '2' , reason = '${reeason}',update_date = `
        let arr1 = [id]
        let row1 = await mysqlHandel(sql1, arr1)
        let sql2 = `select * from porter_user where id = ?`
        let arr2 = [uid]
        let row2 = await mysqlHandel(sql2, arr2)
        const newWithdrawnRewards = Number(row2[0].withdrawn_rewards) - Number(amount); //已提现
        const newRemainingWithdrawableRewards = Number(row2[0].invitation_rewards) - Number(newWithdrawnRewards);//剩余可提现

        let sql3 = `UPDATE porter_user 
             SET withdrawn_rewards = ?,remaining_withdrawable_rewards = ?, update_date = ?
             WHERE id = ?`;
        let arr3 = [newWithdrawnRewards, newRemainingWithdrawableRewards, formatDate(new Date()), uid]
        //用户表加上金额
        let row3 = await mysqlHandel(sql3, arr3)
        res.send({ code: 0, msg: 'success' })

    }
})

//添加资源
router.post('/editMedia', async (req, res) => {
    const { media_name, media_url, id, uid, status, reason, imageUrl, email, nickname, country_id, type_id } = req.body
    let appComment = {}
    if (id) {
        // 更新
        let sql = `UPDATE porter_media SET media_name = ?, media_url = ?, status = ?, reason = ?, media_cover = ?, update_date = ?, country_id = ?, type_id = ? WHERE id = ?`;
        let values = [media_name, media_url, status, reason, imageUrl, utils.formatDate(new Date()), country_id, type_id, id];

        try {
            await mysqlHandel(sql, values);
            res.send({ code: 0, msg: "success" });
        } catch (updateErr) {
            console.log(updateErr,'updateErr')
            res.send(utils.returnData({ code: -1, err: updateErr, req }));
        }
    } else {
        //新增
        appComment.id = utils.createId();
        appComment.uid = uid;
        appComment.media_name = media_name;
        appComment.media_cover = imageUrl;
        appComment.media_url = media_url;
        appComment.email = email;
        appComment.country_id = country_id;
        appComment.type_id = type_id;
        appComment.nickname = nickname;
        appComment.create_date = utils.formatDate(new Date());
        appComment.update_date = utils.formatDate(new Date());

        const { text, values } = utils.createInsertSql(
            "porter_media",
            appComment
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ code: 0, msg: "新增成功" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
})
router.post('/editUser', async (req, res) => {
    const { rate_parameter1, rate_parameter2, rate_parameter3, settlement_type, id } = req.body
    // 更新
    let sql = `UPDATE porter_user SET rate_parameter1 = '${rate_parameter1}' ,rate_parameter2 = '${rate_parameter2}' ,rate_parameter3 = '${rate_parameter3}' ,settlement_type = '${settlement_type}' , update_date = '${formatDate(
        new Date()
    )}' WHERE id = '${id}'`;
    await pool.query(sql, (updateErr, updateResult) => {
        if (updateErr)
            return res.send(utils.returnData({ code: -1, updateErr, req }));
        res.send({ code: 0, msg: "修改成功" });
    });

})

//获取资源的第一条可用链接
router.post('/getMediaLink', async (req, res) => {
    const { id } = req.body
    let sql = `SELECT * FROM porter_link WHERE media_id = ? AND status = 0;`
    let row = await mysqlHandel(sql, [id]);
    res.send(
        utils.returnData({
            data: row,
        })
    );
})
//资源列表  
router.post('/getMediaListAll', async (req, res) => {
    // 从请求体中获取分页和筛选参数
    let { page, size, status, uid, media_name, type_id, country_id, sort } = req.body;
    let paginatedParams = utils.pageSize(page, size);

    // 初始化基础 SQL 查询
    let sql = `FROM porter_media WHERE 1=1`;  // 使用 1=1 作为基础条件
    let arr = [];

    // 根据请求体中是否有特定条件来添加到 SQL 查询中
    if (typeof status !== "undefined") {
        sql += ` AND status = ?`;
        arr.push(status);
    }
    if (typeof uid !== "undefined") {
        sql += ` AND uid = ?`;
        arr.push(uid);
    }
    if (media_name) {
        sql += ` AND media_name LIKE ?`;
        arr.push(`%${media_name}%`);
    }
    if (type_id) {
        sql += ` AND type_id = ?`;
        arr.push(type_id);
    }
    if (country_id) {
        sql += ` AND country_id = ?`;
        arr.push(country_id);
    }

    // SQL 语句用于统计总记录数
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;

    // 根据 `sort` 参数确定排序列
    let orderColumn = sort === 1 ? 'import_totals' : 'update_date';

    // SQL 语句用于获取分页记录，并根据动态排序
    let sqlSelect = `SELECT * ${sql} ORDER BY ${orderColumn} DESC LIMIT ? OFFSET ?`;
    arr.push(paginatedParams.size, paginatedParams.page);

    try {
        // 获取记录总数
        let totalRes = await mysqlHandel(sqlCount, arr.slice(0, -2)); // 对计数查询使用不包含分页参数的 arr
        let total = totalRes[0].total_count;

        // 获取分页记录
        let row = await mysqlHandel(sqlSelect, arr);

        // 处理每一行记录以便响应
        row.forEach((element) => {
            if (!element.reason) {
                element.reason = '-';
            }
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            if (element.revenue_totals) {
                element.revenue_totals = element.revenue_totals.toFixed(6);
            }
            element.imgList = [];
            if (element.media_cover) {
                element.imgList.push(element.media_cover);
            }
        });

        // 发送响应，包含分页数据和总记录数
        res.send(
            utils.returnData({
                data: row,
                total: total,
            })
        );
    } catch (error) {
        // 记录错误并发送错误响应
        console.error("Error fetching media list:", error);
        res.status(500).send(
            utils.returnData({
                error: "Error fetching media list",
            })
        );
    }
});
router.post('/getMediaListAll1', async (req, res) => {
    let sql = `select * from porter_media`
    let res1 = await mysqlHandel(sql);
    console.log(res1)
    // 预定义的 type_id 列表
    const typeIds = [
        '7231556724098859008',
        '7231610477594279936',
        '7231610501883494400',
        '7231610524645982208',
        '7231610548196999168',
        '7231610572024840192',
        '7231610595844292608',
    ];
    // 对每条记录，随机选择一个 type_id 更新
    for (const record of res1) {
        const randomTypeId = typeIds[Math.floor(Math.random() * typeIds.length)];
        const updateSql = `UPDATE porter_media SET country_id = ? WHERE id = ?`;
        let s= await mysqlHandel(updateSql, [randomTypeId, record.id]);
        console.log(s)
    }
});
router.post('/getMediaList', async (req, res) => {
    // Retrieve pagination parameters from request body using a utility function
    let { page, size } = utils.pageSize(req.body.page, req.body.size);

    // Extract the uid from the request body
    const { uid } = req.body;

    // Initialize the base SQL query
    let sql = `FROM porter_media WHERE uid = ?`;
    let arr = [uid];

    // SQL to count the total number of records
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;

    // SQL to select the paginated records with ordering
    let sqlSelect = `SELECT * ${sql} ORDER BY update_date DESC LIMIT ? OFFSET ?`;
    arr.push(size, page);

    try {
        // Fetch the total count of records
        let totalRes = await mysqlHandel(sqlCount, [uid]);
        let total = totalRes[0].total_count;

        // Fetch the paginated records
        let row = await mysqlHandel(sqlSelect, arr);

        // Process each row for the response
        row.forEach((element) => {
            if (!element.reason) {
                element.reason = '-';
            }
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            if (element.revenue_totals) {
                element.revenue_totals = element.revenue_totals.toFixed(6);
            }
            element.imgList = [];
            if (element.media_cover) {
                element.imgList.push(element.media_cover);
            }
        });

        // Send the response with paginated data and total count
        res.send(
            utils.returnData({
                data: row,
                total: total,
            })
        );
    } catch (error) {
        // Log the error and send an error response
        console.error("Error fetching media list:", error);
        res.status(500).send(
            utils.returnData({
                error: "Error fetching media list",
            })
        );
    }
});
router.post("/test", async (req, res) => {
    console.log('---------test')
    res.send({ code: 0, msg: "111接口部署成功" });
});
router.get('/deeplink', (req, res) => {
    const indexPath = path.join(__dirname, '../', 'index.html');
    res.sendFile(indexPath);
});
//生成链接
router.post('/createLink', async (req, res) => {
    const { id, uid, media_url, media_name } = req.body //id = 资源id uid = 用户id
    // www.baidu.com/node/porter/deeplink?uid=uid&media_id=id
    let appComment = {}
    appComment.id = utils.createId();
    appComment.uid = uid;
    appComment.media_id = id;
    appComment.media_url = media_url;
    appComment.media_name = media_name;
    appComment.create_date = utils.formatDate(new Date());
    appComment.update_date = utils.formatDate(new Date());
    appComment.link_url = `https://chatai-pro.wecall.info/node/porter/deeplink?uid=${uid}&media_id=${id}&link_id=${appComment.id}`
    const { text, values } = utils.createInsertSql(
        "porter_link",
        appComment
    );
    let result = await utils.query(text, values);
    if (result.affectedRows == 1) {
        res.send({ code: 0, msg: "新增成功" });
    } else {
        res.send(utils.returnData({ code: -1, err, req }));
    }

})
//链接禁用启用
router.post('/editLink', async (req, res) => {
    const { id, status } = req.body
    sqlUpdate = `update porter_link set status = ? where id = ?`
    let arr = [status, id]
    let updateRow = await mysqlHandel(sqlUpdate, arr)
    res.send({ code: 0, msg: 'success' })
})
//获取链接列表
router.post('/getLinkList', async (req, res) => {
    // 从请求体中获取分页参数
    const { page, size, uid, media_id } = req.body;
    const paginatedParams = utils.pageSize(page, size);

    // 用于获取记录总数的 SQL 查询
    const sqlCount = `SELECT COUNT(*) AS total_count FROM porter_link WHERE uid = ? AND media_id = ?`;
    const countParams = [uid, media_id];

    // 用于分页获取记录的 SQL 查询
    const sqlSelect = `
        SELECT * FROM porter_link 
        WHERE uid = ? AND media_id = ?
        LIMIT ? OFFSET ?`;
    const selectParams = [uid, media_id, paginatedParams.size, paginatedParams.page];

    try {
        // 获取记录总数
        const totalRes = await mysqlHandel(sqlCount, countParams);
        const total = totalRes[0].total_count;

        // 获取分页记录
        const rows = await mysqlHandel(sqlSelect, selectParams);

        // 格式化返回的数据
        rows.forEach(element => {
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            if (element.revenue_total) {
                element.revenue_total = element.revenue_total.toFixed(6);
            }
        });

        // 返回分页数据和总记录数
        res.send(
            utils.returnData({
                data: rows,
                total: total
            })
        );
    } catch (error) {
        // 记录错误并发送错误响应
        console.error("Error fetching link list:", error);
        res.status(500).send(
            utils.returnData({
                error: "Error fetching link list"
            })
        );
    }
});

//获取资源类型
router.post('/getMediaType', async (req, res) => {
    let sql = `select * from media_type where state = '0'`
    let result = await mysqlHandel(sql)
    res.send({
        code: 0,
        data: result,
        msg: 'success'
    })
})

//添加修改类型
router.post('/editMediaType', async (req, res) => {
    const { id, type, state } = req.body
    let record = {}
    if (id) {
        // 更新
        let sql = `update media_type set type = '${type}',state='${state}',update_date = '${formatDate(
            new Date()
        )}' WHERE id = '${id}'`;
        await pool.query(sql, (updateErr, updateResult) => {
            if (updateErr)
                return res.send(utils.returnData({ code: -1, updateErr, req }));
            res.send({ code: 0, msg: "success" });
        });
    } else {
        //新增
        record.id = utils.createId();
        record.type = type;
        record.create_date = utils.formatDate(new Date());
        record.update_date = utils.formatDate(new Date());

        const { text, values } = utils.createInsertSql(
            "media_type",
            record
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ code: 0, msg: "success" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
})
//获取资源地区
router.post('/getMediaCity', async (req, res) => {
    let sql = `select * from media_city where state = '0'`
    let result = await mysqlHandel(sql)
    res.send({
        code: 0,
        data: result,
        msg: 'success'
    })
})

//添加修改类型
router.post('/editMediaCity', async (req, res) => {
    const { id, city, state } = req.body
    let record = {}
    if (id) {
        // 更新
        let sql = `update media_city set city = '${city}',state='${state}',update_date = '${formatDate(
            new Date()
        )}' WHERE id = '${id}'`;
        await pool.query(sql, (updateErr, updateResult) => {
            if (updateErr)
                return res.send(utils.returnData({ code: -1, updateErr, req }));
            res.send({ code: 0, msg: "success" });
        });
    } else {
        //新增
        record.id = utils.createId();
        record.city = city;
        record.create_date = utils.formatDate(new Date());
        record.update_date = utils.formatDate(new Date());

        const { text, values } = utils.createInsertSql(
            "media_city",
            record
        );
        let result = await utils.query(text, values);
        if (result.affectedRows == 1) {
            res.send({ code: 0, msg: "success" });
        } else {
            res.send(utils.returnData({ code: -1, err, req }));
        }
    }
})
//获取资源地址
router.post('/getMediaUrl', async (req, res) => {
    const { id, media_id, uid } = req.body //id =链接id
    //先查 链接 的 视频资源状态 能不能播   资源表 和 链接表  状态都正常 才能播  否则 资源已禁用
    let sql = `select * from porter_link where id = ?`
    let arr = [id]
    let result = await mysqlHandel(sql, arr)
    if (result[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' })
    let sql1 = `select * from porter_media where id = ?`
    let arr1 = [media_id]
    let result1 = await mysqlHandel(sql, arr)
    if (result1[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' })
    res.send({
        code: 0,
        media_url: result[0].media_url,
        msg: '操作成功'
    })
})

//用户行为记录  导入
router.post('/trackUserActivityParse', async (req, res) => {
    let { id, uid } = req.body
    // id 链接id uid 用户id  parse 导入次数 play 播放次数 adView 观看广告次数

    try {
        let sql = `select * from porter_link where id = ?`
        let arr = [id]
        let result = await mysqlHandel(sql, arr)
        if (result[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' })
        let sql1 = `select * from porter_media where id = ?`
        let arr1 = [result[0].media_id]
        let result1 = await mysqlHandel(sql1, arr1)
        if (result1[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' })
        if (result1[0].status != 0) return res.send({ code: 1, msg: 'success!' })


        let import_total = Number(result[0].import_total) + 1

        // 更新链接表 
        let sql2 = `update porter_link set import_total = ? , update_date = ?
             WHERE id = ?`
        let arr2 = [import_total, utils.formatDate(new Date()), id]
        let result2 = await mysqlHandel(sql2, arr2)

        //更新资源表
        let import_totals = Number(result1[0].import_totals) + 1

        let sql3 = `update porter_media set import_totals = ? ,   update_date = ?
             WHERE id = ?`
        let arr3 = [import_totals, utils.formatDate(new Date()), result[0].media_id]
        let result3 = await mysqlHandel(sql3, arr3)
        res.send({ code: 0, msg: '操作成功' })
    } catch (error) {
        res.send({ code: 1, msg: error.message })
    }

})
// 播放
router.post('/trackUserActivityPlay', async (req, res) => {
    let { id, uid } = req.body
    // id 链接id uid 用户id  parse 导入次数 play 播放次数 adView 观看广告次数

    try {
        let sql = `select * from porter_link where id = ?`
        let arr = [id]
        let result = await mysqlHandel(sql, arr)
        if (result[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' })
        let sql1 = `select * from porter_media where id = ?`
        let arr1 = [result[0].media_id]
        let result1 = await mysqlHandel(sql1, arr1)
        if (result1[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' })



        let play_total = Number(result[0].play_total) + 1

        // 更新链接表
        let sql2 = `update porter_link set   play_total = ? ,   update_date = ?
             WHERE id = ?`
        let arr2 = [play_total, utils.formatDate(new Date()), id]
        let result2 = await mysqlHandel(sql2, arr2)

        //更新资源表
        let play_totals = Number(result1[0].play_totals) + 1

        let sql3 = `update porter_media set   play_totals = ?  , update_date = ?
             WHERE id = ?`
        let arr3 = [play_totals, utils.formatDate(new Date()), result[0].media_id]
        let result3 = await mysqlHandel(sql3, arr3)
        res.send({ code: 0, msg: '操作成功' })
    } catch (error) {
        res.send({ code: 1, msg: error.message })
    }

})
//看广告
// router.post('/trackUserActivityAdView', async (req, res) => {
//     let { id, uid, income } = req.body
//     // id 链接id uid 用户id  parse 导入次数 play 播放次数 adView 观看广告次数

//     try {
//         let sql = `select * from porter_link where id = ?`
//         let arr = [id]
//         let result = await mysqlHandel(sql, arr)
//         if (result[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' })
//         let sql1 = `select * from porter_media where id = ?`
//         let arr1 = [result[0].media_id]
//         let result1 = await mysqlHandel(sql1, arr1)
//         if (result1[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' })
//         //查询用户表 看计算公式 和 结算类型
//         let sql4 = `select * from porter_user where id = ?`
//         let arr4 = [uid]
//         let result4 = await mysqlHandel(sql4, arr4)

//         let settlement_type = result4[0].settlement_type // 结算类型  0 是每次 1是每千次
//         let count_threshold = result4[0].count_threshold // 千次 累计次数
//         let rate_parameter1 = result4[0].rate_parameter1 // 计算参数
//         let rate_parameter2 = result4[0].rate_parameter2 // 计算参数
//         let rate_parameter3 = result4[0].rate_parameter3 // 计算参数
//         let fee = result4[0].fee // 千次累计佣金

//         let revenue_total = result[0].revenue_total //单条链接总收入
//         let revenue_totals = result1[0].revenue_totals //资源表的总收入
//         let invitation_rewards = Number(result4[0].invitation_rewards) //用户表的总收入


//         //增加观看次数
//         let adView_total = Number(result[0].adView_total) + 1

//         //查询是哪种结算方式
//         if (settlement_type == 0) {
//             //单词结算
//             //查询有没有累计次数
//             if (Number(count_threshold) > 0) {
//                 //有累计次数 计算返佣
//                 // 链接表
//                 //累计千次佣金
//                 fee = Number(fee) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 revenue_total = Number(result[0].revenue_total) + Number(fee)
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(fee)
//                 invitation_rewards = Number(result4[0].invitation_rewards) + Number(fee)
//             } else {
//                 //没有累计次数 计算返佣
//                 // 链接表
//                 revenue_total = Number(result[0].revenue_total) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 //资源表
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 //用户表
//                 invitation_rewards = Number(result4[0].invitation_rewards) + (Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3)))
//             }

//             // 更新链接表
//             let sql2 = `update porter_link set adView_total = ? , revenue_total = ?, update_date = ?
//              WHERE id = ?`
//             let arr2 = [adView_total, revenue_total, utils.formatDate(new Date()), id]
//             let result2 = await mysqlHandel(sql2, arr2)

//             //更新资源表
//             let adView_totals = Number(result1[0].adView_totals) + 1

//             let sql3 = `update porter_media set   adView_totals = ? , revenue_totals = ?, update_date = ?
//              WHERE id = ?`
//             let arr3 = [adView_totals, revenue_totals, utils.formatDate(new Date()), result[0].media_id]
//             let result3 = await mysqlHandel(sql3, arr3)

//             //如果观看广告了 更新用户表

//             let remaining_withdrawable_rewards = Number(invitation_rewards) - Number(result4[0].withdrawn_rewards)
//             let sql5 = `update porter_user set invitation_rewards = ? , remaining_withdrawable_rewards = ?,count_threshold=?, fee = ?, update_date = ?
//              WHERE id = ?`

//             let arr5 = [invitation_rewards, remaining_withdrawable_rewards, 0,0, utils.formatDate(new Date()), uid]

//             let result5 = await mysqlHandel(sql5, arr5)
//             res.send({ code: 0, msg: '操作成功' })

//         } else {
//             //千次结算
//             //增加阈值累计次数
//             count_threshold = Number(count_threshold) + 1
//             //累计千次佣金
//             console.log('jin', fee)

//             fee = Number(fee) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//             console.log('jin',fee)
//             if (count_threshold == 1000) {

//                 // 计算返佣
//                 revenue_total = Number(result[0].revenue_total) +  Number(fee)


//                 // 更新链接表
//                 let sql2 = `update porter_link set adView_total = ? , revenue_total = ?, update_date = ?
//              WHERE id = ?`
//                 let arr2 = [adView_total, revenue_total, utils.formatDate(new Date()), id]
//                 let result2 = await mysqlHandel(sql2, arr2)

//                 //更新资源表
//                 let adView_totals = Number(result1[0].adView_totals) + 1
//                 let revenue_totals = result1[0].revenue_totals
//                 //观看广告了 加收入
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(fee)
//                 let sql3 = `update porter_media set   adView_totals = ? , revenue_totals = ?, update_date = ?
//              WHERE id = ?`
//                 let arr3 = [adView_totals, revenue_totals, utils.formatDate(new Date()), result[0].media_id]
//                 let result3 = await mysqlHandel(sql3, arr3)

//                 //如果观看广告了 更新用户表

//                 let invitation_rewards = Number(result4[0].invitation_rewards) + Number(fee)
//                 let remaining_withdrawable_rewards = Number(invitation_rewards) - Number(result4[0].withdrawn_rewards)
//                 let sql5 = `update porter_user set invitation_rewards = ? , remaining_withdrawable_rewards = ?,count_threshold=?, fee=?, update_date = ?
//              WHERE id = ?`

//                 let arr5 = [invitation_rewards, remaining_withdrawable_rewards, 0,0, utils.formatDate(new Date()), uid]

//                 let result5 = await mysqlHandel(sql5, arr5)


//             } else {
//                 //只累计次数
//                 // 更新链接表
//                 let sql2 = `update porter_link set adView_total = ? , update_date = ?
//              WHERE id = ?`
//                 let arr2 = [adView_total, utils.formatDate(new Date()), id]
//                 let result2 = await mysqlHandel(sql2, arr2)

//                 //更新资源表
//                 let adView_totals = Number(result1[0].adView_totals) + 1
//                 let sql3 = `update porter_media set   adView_totals = ? ,   update_date = ?
//              WHERE id = ?`
//                 let arr3 = [adView_totals, utils.formatDate(new Date()), result[0].media_id]
//                 let result3 = await mysqlHandel(sql3, arr3)

//                 //更新用户表
//                 let sql5 = `update porter_user set count_threshold=?, fee = ?, update_date = ?
//              WHERE id = ?`
//                 let arr5 = [count_threshold,fee, utils.formatDate(new Date()), uid]
//                 console.log(fee,'feeeeeeee')
//                 let result5 = await mysqlHandel(sql5, arr5)
//                 console.log(result5,'result5')
//             }
//             res.send({ code: 0, msg: '操作成功' })
//         }
//     } catch (error) {
//         res.send({ code: 1, msg: error.message })
//     }
// })
router.post('/trackUserActivityAdView', async (req, res) => {
    let { id, uid, income } = req.body;
    try {
        // 获取链接、资源和用户信息


        let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
        let linkResult = await mysqlHandel(linkQuery, [id]);

        if (linkResult[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' });

        let mediaQuery = `SELECT * FROM porter_media WHERE id = ?`;
        let mediaResult = await mysqlHandel(mediaQuery, [linkResult[0].media_id]);

        if (mediaResult[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' });

        let userQuery = `SELECT * FROM porter_user WHERE id = ?`;
        let userResult = await mysqlHandel(userQuery, [uid]);

        let { settlement_type, count_threshold, rate_parameter1, rate_parameter2, rate_parameter3 } = userResult[0];
        let { revenue_total, link_fee } = linkResult[0];
        let { revenue_totals, media_fee } = mediaResult[0];
        let invitation_rewards = Number(userResult[0].invitation_rewards);

        // 增加观看次数
        let adView_total = Number(linkResult[0].adView_total) + 1;
        let adView_totals = Number(mediaResult[0].adView_totals) + 1;

        // 计算佣金
        let calculated_fee = Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3));

        if (settlement_type == 0) {
            // 单次结算
            if (Number(count_threshold) > 0) {
                // 更新所有链接和媒体的 fee 到 revenue_total 和 revenue_totals
                let allLinksQuery = `SELECT id, link_fee FROM porter_link WHERE link_fee > 0`;
                let allLinksResult = await mysqlHandel(allLinksQuery);
                for (let link of allLinksResult) { //原有0.5 把fee加进去0.5
                    let updateLinkRevenueQuery = `UPDATE porter_link SET revenue_total = revenue_total + ?, link_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateLinkRevenueQuery, [link.link_fee, link.id]);

                    invitation_rewards += link.link_fee;
                }
                let allMediaQuery = `SELECT id, media_fee FROM porter_media WHERE media_fee > 0`;
                let allMediaResult = await mysqlHandel(allMediaQuery);

                for (let media of allMediaResult) {
                    let updateMediaRevenueQuery = `UPDATE porter_media SET revenue_totals = revenue_totals + ?, media_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateMediaRevenueQuery, [media.media_fee, media.id]);
                }
                let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
                let linkResult = await mysqlHandel(linkQuery, [id]);
                revenue_total = linkResult[0].revenue_total
                revenue_total += calculated_fee;


                media_fee += calculated_fee;
                revenue_totals += media_fee;
                invitation_rewards += calculated_fee;



            } else {
                revenue_total += calculated_fee;
                revenue_totals += calculated_fee;
                invitation_rewards += calculated_fee;
            }
            link_fee = 0;
            media_fee = 0;
            count_threshold = 0; // 重置累计次数
        } else {
            // 千次结算
            count_threshold += 1;
            link_fee += calculated_fee;
            media_fee += calculated_fee; // 当前存量加上返佣

            if (count_threshold == 20) {
                // 更新所有链接和媒体的 fee 到 revenue_total 和 revenue_totals
                let allLinksQuery = `SELECT id, link_fee FROM porter_link WHERE link_fee > 0`;
                let allLinksResult = await mysqlHandel(allLinksQuery);

                for (let link of allLinksResult) {
                    let updateLinkRevenueQuery = `UPDATE porter_link SET revenue_total = revenue_total + ?, link_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateLinkRevenueQuery, [link.link_fee, link.id]);
                    invitation_rewards += link.link_fee; // 累加所有链接的 fee
                }

                let allMediaQuery = `SELECT id, media_fee FROM porter_media WHERE media_fee > 0`;
                let allMediaResult = await mysqlHandel(allMediaQuery);


                for (let media of allMediaResult) {
                    let updateMediaRevenueQuery = `UPDATE porter_media SET revenue_totals = revenue_totals + ?,media_fee=0 WHERE id = ?`;
                    await mysqlHandel(updateMediaRevenueQuery, [media.media_fee, media.id]);
                    // revenue_totals += media.media_fee; // 更新 revenue_totals
                }

                revenue_totals = mediaResult[0].revenue_totals
                revenue_totals += mediaResult[0].media_fee;
                revenue_totals += calculated_fee;
                let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
                let linkResult = await mysqlHandel(linkQuery, [id]);
                revenue_total = linkResult[0].revenue_total
                revenue_total += calculated_fee;


                invitation_rewards += calculated_fee;
                count_threshold = 0; // 重置累计次数
                link_fee = 0; // 重置累计佣金
                media_fee = 0; // 重置累计佣金
            }
        }

        // 更新数据库
        let updateLinkQuery = `UPDATE porter_link SET adView_total = ?, revenue_total = ?, link_fee = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateLinkQuery, [adView_total, revenue_total, link_fee, utils.formatDate(new Date()), id]);

        let updateMediaQuery = `UPDATE porter_media SET adView_totals = ?, revenue_totals = ?, media_fee = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateMediaQuery, [adView_totals, revenue_totals, media_fee, utils.formatDate(new Date()), linkResult[0].media_id]);

        let remaining_withdrawable_rewards = invitation_rewards - Number(userResult[0].withdrawn_rewards);
        invitation_rewards = parseFloat(invitation_rewards.toFixed(6));
        let updateUserQuery = `UPDATE porter_user SET invitation_rewards = ?, remaining_withdrawable_rewards = ?, count_threshold = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateUserQuery, [invitation_rewards, remaining_withdrawable_rewards, count_threshold, utils.formatDate(new Date()), uid]);
        res.send({ code: 0, msg: '操作成功' });
    } catch (error) {
        console.log(error)
        res.send({ code: 1, msg: error.message });
    }
});


//点击广告
// router.post('/trackUserActivityAdViewClick', async (req, res) => {
//     let { id, uid, income } = req.body
//     // id 链接id uid 用户id  parse 导入次数 play 播放次数 adView 观看广告次数

//     try {
//         let sql = `select * from porter_link where id = ?`
//         let arr = [id]
//         let result = await mysqlHandel(sql, arr)
//         if (result[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' })
//         let sql1 = `select * from porter_media where id = ?`
//         let arr1 = [result[0].media_id]
//         let result1 = await mysqlHandel(sql1, arr1)
//         if (result1[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' })
//         //查询用户表 看计算公式 和 结算类型
//         let sql4 = `select * from porter_user where id = ?`
//         let arr4 = [uid]
//         let result4 = await mysqlHandel(sql4, arr4)

//         let settlement_type = result4[0].settlement_type // 结算类型  0 是每次 1是每千次
//         let count_threshold = result4[0].count_threshold // 千次 累计次数
//         let rate_parameter1 = result4[0].rate_parameter1 // 计算参数
//         let rate_parameter2 = result4[0].rate_parameter2 // 计算参数
//         let rate_parameter3 = result4[0].rate_parameter3 // 计算参数
//         let fee = result4[0].fee // 千次累计佣金

//         let revenue_total = result[0].revenue_total //单条链接总收入
//         let revenue_totals = result1[0].revenue_totals //资源表的总收入
//         let invitation_rewards = Number(result4[0].invitation_rewards) //用户表的总收入


//         //增加观看次数
//         let adView_click_total = Number(result[0].adView_click_total) + 1

//         //查询是哪种结算方式
//         if (settlement_type == 0) {
//             //单词结算
//             //查询有没有累计次数
//             if (Number(count_threshold) > 0) {
//                 //有累计次数 计算返佣
//                 // 链接表
//                 //累计千次佣金
//                 fee = Number(fee) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 revenue_total = Number(result[0].revenue_total) + Number(fee)
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(fee)
//                 invitation_rewards = Number(result4[0].invitation_rewards) + Number(fee)
//             } else {
//                 //没有累计次数 计算返佣
//                 // 链接表
//                 revenue_total = Number(result[0].revenue_total) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 //资源表
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//                 //用户表
//                 invitation_rewards = Number(result4[0].invitation_rewards) + (Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3)))
//             }

//             // 更新链接表
//             let sql2 = `update porter_link set adView_click_total = ? , revenue_total = ?, update_date = ?
//              WHERE id = ?`
//             let arr2 = [adView_click_total, revenue_total, utils.formatDate(new Date()), id]
//             let result2 = await mysqlHandel(sql2, arr2)

//             //更新资源表
//             let adView_click_totals = Number(result1[0].adView_click_totals) + 1

//             let sql3 = `update porter_media set   adView_click_totals = ? , revenue_totals = ?, update_date = ?
//              WHERE id = ?`
//             let arr3 = [adView_click_totals, revenue_totals, utils.formatDate(new Date()), result[0].media_id]
//             let result3 = await mysqlHandel(sql3, arr3)

//             //如果观看广告了 更新用户表

//             let remaining_withdrawable_rewards = Number(invitation_rewards) - Number(result4[0].withdrawn_rewards)
//             let sql5 = `update porter_user set invitation_rewards = ? , remaining_withdrawable_rewards = ?,count_threshold=?, fee = ?, update_date = ?
//              WHERE id = ?`

//             let arr5 = [invitation_rewards, remaining_withdrawable_rewards, 0, 0, utils.formatDate(new Date()), uid]

//             let result5 = await mysqlHandel(sql5, arr5)
//             res.send({ code: 0, msg: '操作成功' })

//         } else {
//             //千次结算
//             //增加阈值累计次数
//             count_threshold = Number(count_threshold) + 1
//             //累计千次佣金
//             fee = Number(fee) + Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3))
//             if (count_threshold == 1000) {

//                 // 计算返佣
//                 revenue_total = Number(result[0].revenue_total) + Number(fee)


//                 // 更新链接表
//                 let sql2 = `update porter_link set adView_total = ? , revenue_total = ?, update_date = ?
//              WHERE id = ?`
//                 let arr2 = [adView_total, revenue_total, utils.formatDate(new Date()), id]
//                 let result2 = await mysqlHandel(sql2, arr2)

//                 //更新资源表
//                 let adView_click_totals = Number(result1[0].adView_click_totals) + 1
//                 let revenue_totals = result1[0].revenue_totals
//                 //观看广告了 加收入
//                 revenue_totals = Number(result1[0].revenue_totals) + Number(fee)
//                 let sql3 = `update porter_media set   adView_click_totals = ? , revenue_totals = ?, update_date = ?
//              WHERE id = ?`
//                 let arr3 = [adView_click_totals, revenue_totals, utils.formatDate(new Date()), result[0].media_id]
//                 let result3 = await mysqlHandel(sql3, arr3)

//                 //如果观看广告了 更新用户表

//                 let invitation_rewards = Number(result4[0].invitation_rewards) + Number(fee)
//                 let remaining_withdrawable_rewards = Number(invitation_rewards) - Number(result4[0].withdrawn_rewards)
//                 let sql5 = `update porter_user set invitation_rewards = ? , remaining_withdrawable_rewards = ?,count_threshold=?, fee=?, update_date = ?
//              WHERE id = ?`

//                 let arr5 = [invitation_rewards, remaining_withdrawable_rewards, 0, 0, utils.formatDate(new Date()), uid]

//                 let result5 = await mysqlHandel(sql5, arr5)


//             } else {
//                 //只累计次数
//                 // 更新链接表
//                 let sql2 = `update porter_link set adView_total = ? , update_date = ?
//              WHERE id = ?`
//                 let arr2 = [adView_total, utils.formatDate(new Date()), id]
//                 let result2 = await mysqlHandel(sql2, arr2)

//                 //更新资源表
//                 let adView_click_totals = Number(result1[0].adView_click_totals) + 1
//                 let sql3 = `update porter_media set   adView_click_totals = ? ,   update_date = ?
//              WHERE id = ?`
//                 let arr3 = [adView_click_totals, utils.formatDate(new Date()), result[0].media_id]
//                 let result3 = await mysqlHandel(sql3, arr3)

//                 //更新用户表
//                 let sql5 = `update porter_user set count_threshold=?, fee = ?, update_date = ?
//              WHERE id = ?`
//                 let arr5 = [count_threshold, fee, utils.formatDate(new Date()), uid]

//                 let result5 = await mysqlHandel(sql5, arr5)
//             }
//             res.send({ code: 0, msg: '操作成功' })
//         }
//     } catch (error) {
//         res.send({ code: 1, msg: error.message })
//     }




// })
router.post('/trackUserActivityAdViewClick', async (req, res) => {
    let { id, uid, income } = req.body;

    try {
        // 获取链接、资源和用户信息

        let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
        let linkResult = await mysqlHandel(linkQuery, [id]);

        if (linkResult[0].status != 0) return res.send({ code: 1, msg: '链接已被禁用' });

        let mediaQuery = `SELECT * FROM porter_media WHERE id = ?`;
        let mediaResult = await mysqlHandel(mediaQuery, [linkResult[0].media_id]);

        if (mediaResult[0].status != 0) return res.send({ code: 1, msg: '资源已被禁用' });

        let userQuery = `SELECT * FROM porter_user WHERE id = ?`;
        let userResult = await mysqlHandel(userQuery, [uid]);

        let { settlement_type, count_threshold, rate_parameter1, rate_parameter2, rate_parameter3 } = userResult[0];
        let { revenue_total, link_fee } = linkResult[0];
        let { revenue_totals, media_fee } = mediaResult[0];
        let invitation_rewards = Number(userResult[0].invitation_rewards);

        // 增加观看次数
        let adView_click_total = Number(linkResult[0].adView_click_total) + 1;
        let adView_click_totals = Number(mediaResult[0].adView_click_totals) + 1;

        // 计算佣金
        let calculated_fee = Number(income) * (Number(rate_parameter1) / Number(rate_parameter2) * Number(rate_parameter3));

        if (settlement_type == 0) {
            // 单次结算
            if (Number(count_threshold) > 0) {
                // 更新所有链接和媒体的 fee 到 revenue_total 和 revenue_totals
                let allLinksQuery = `SELECT id, link_fee FROM porter_link WHERE link_fee > 0`;
                let allLinksResult = await mysqlHandel(allLinksQuery);
                for (let link of allLinksResult) { //原有0.5 把fee加进去0.5
                    let updateLinkRevenueQuery = `UPDATE porter_link SET revenue_total = revenue_total + ?, link_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateLinkRevenueQuery, [link.link_fee, link.id]);

                    invitation_rewards += link.link_fee;
                }
                let allMediaQuery = `SELECT id, media_fee FROM porter_media WHERE media_fee > 0`;
                let allMediaResult = await mysqlHandel(allMediaQuery);

                for (let media of allMediaResult) {
                    let updateMediaRevenueQuery = `UPDATE porter_media SET revenue_totals = revenue_totals + ?, media_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateMediaRevenueQuery, [media.media_fee, media.id]);
                }
                let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
                let linkResult = await mysqlHandel(linkQuery, [id]);
                revenue_total = linkResult[0].revenue_total
                revenue_total += calculated_fee;


                media_fee += calculated_fee;
                revenue_totals += media_fee;
                invitation_rewards += calculated_fee;



            } else {
                revenue_total += calculated_fee;
                revenue_totals += calculated_fee;
                invitation_rewards += calculated_fee;
            }
            link_fee = 0;
            media_fee = 0;
            count_threshold = 0; // 重置累计次数
        } else {
            // 千次结算
            count_threshold += 1;
            link_fee += calculated_fee;
            media_fee += calculated_fee; // 当前存量加上返佣

            if (count_threshold == 20) {
                // 更新所有链接和媒体的 fee 到 revenue_total 和 revenue_totals
                let allLinksQuery = `SELECT id, link_fee FROM porter_link WHERE link_fee > 0`;
                let allLinksResult = await mysqlHandel(allLinksQuery);

                for (let link of allLinksResult) {
                    let updateLinkRevenueQuery = `UPDATE porter_link SET revenue_total = revenue_total + ?, link_fee = 0 WHERE id = ?`;
                    await mysqlHandel(updateLinkRevenueQuery, [link.link_fee, link.id]);
                    invitation_rewards += link.link_fee; // 累加所有链接的 fee
                }

                let allMediaQuery = `SELECT id, media_fee FROM porter_media WHERE media_fee > 0`;
                let allMediaResult = await mysqlHandel(allMediaQuery);


                for (let media of allMediaResult) {
                    let updateMediaRevenueQuery = `UPDATE porter_media SET revenue_totals = revenue_totals + ?,media_fee=0 WHERE id = ?`;
                    await mysqlHandel(updateMediaRevenueQuery, [media.media_fee, media.id]);
                    // revenue_totals += media.media_fee; // 更新 revenue_totals
                }

                revenue_totals = mediaResult[0].revenue_totals
                revenue_totals += mediaResult[0].media_fee;
                revenue_totals += calculated_fee;
                let linkQuery = `SELECT * FROM porter_link WHERE id = ?`;
                let linkResult = await mysqlHandel(linkQuery, [id]);
                revenue_total = linkResult[0].revenue_total
                revenue_total += calculated_fee;


                invitation_rewards += calculated_fee;
                count_threshold = 0; // 重置累计次数
                link_fee = 0; // 重置累计佣金
                media_fee = 0; // 重置累计佣金
            }
        }

        // 更新数据库
        let updateLinkQuery = `UPDATE porter_link SET adView_click_total = ?, revenue_total = ?, link_fee = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateLinkQuery, [adView_click_total, revenue_total, link_fee, utils.formatDate(new Date()), id]);

        let updateMediaQuery = `UPDATE porter_media SET adView_click_totals = ?, revenue_totals = ?, media_fee = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateMediaQuery, [adView_click_totals, revenue_totals, media_fee, utils.formatDate(new Date()), linkResult[0].media_id]);
        invitation_rewards = parseFloat(invitation_rewards.toFixed(6));
        let remaining_withdrawable_rewards = invitation_rewards - Number(userResult[0].withdrawn_rewards);
        let updateUserQuery = `UPDATE porter_user SET invitation_rewards = ?, remaining_withdrawable_rewards = ?, count_threshold = ?, update_date = ? WHERE id = ?`;
        await mysqlHandel(updateUserQuery, [invitation_rewards, remaining_withdrawable_rewards, count_threshold, utils.formatDate(new Date()), uid]);
        res.send({ code: 0, msg: '操作成功' });
    } catch (error) {
        console.log(error)
        res.send({ code: 1, msg: error.message });
    }
});

async function mysqlHandel(sql, data) {
    return new Promise((resolve, reject) => {
        pool.query(sql, data, (error, results, fields) => {
            console.log(error)
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
function formatDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    const seconds = date.getSeconds().toString().padStart(2, "0");

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}



module.exports = router;